package com.navi168.fwq21.friend;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.amap.a.k.t;
import com.navi168.fwq21.R;
import com.navi168.fwq21.db.Sqlh;
import com.navi168.fwq21.friend.mod.Cheji;
import com.navi168.fwq21.friend.mod.Myfriend;
import com.navi168.fwq21.hyzl.SendList;
import com.navi168.fwq21.hyzl.SendList.MyAdapter;
import com.navi168.fwq21.hyzl.SendList.ViewHolder;
import com.navi168.fwq21.util.Constants;
import com.navi168.fwq21.util.SendPosition;

import android.R.integer;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class FriendAct extends ActivityGroup {
	private Button newfriend;
	private Button sendmesButton;
	private Button synButton;
	private Button invetButton;
	private Sqlh sqlh;
	private ArrayList<Myfriend> myfriends = new ArrayList<Myfriend>();
	private Context context;
	private MyAdapter mAdapter;
	private ListView friendsListView;
	private String[] number_arry = new String[2];
	private HashMap<String, String> numbermap = new HashMap<String, String>();// 接受的号码
	private HashMap<String, String> namemap = new HashMap<String, String>();
	private String twonumber;
	private int isenable = 0;

	private HashMap<String, String> friendnumber = new HashMap<String, String>();
	private Context mContext = null;
	private ProgressDialog progDialog;
	private int numer = 0;
	private Hashtable<String, TableRow> trs = new Hashtable<String, TableRow>();
//	private ArrayList<EditText> ets = new ArrayList<EditText>();
	private Hashtable<String, EditText> editHashtable = new Hashtable<String, EditText>();
	private static final String[] PHONES_PROJECTION = new String[] {
			Phone.DISPLAY_NAME, Phone.NUMBER };
	/** 联系人显示名称 **/
	private static final int PHONES_DISPLAY_NAME_INDEX = 0;

	/** 电话号码 **/
	private static final int PHONES_NUMBER_INDEX = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.friendlist2);
		progDialog = new ProgressDialog(this);
		findViews();
		setlisters();
		sqlh = sqlh.getInstance(FriendAct.this);

		myfriends = sqlh.getMyfriends();
		context = getApplicationContext();
		mAdapter = new MyAdapter();
		friendsListView.setAdapter(mAdapter);
	}

	private void showToast(String showString) {
		Toast.makeText(getApplicationContext(), showString, Toast.LENGTH_SHORT)
				.show();
	}

	private void setlisters() {

		synButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				progDialog.setIndeterminate(false);
				progDialog.setCancelable(true);
				progDialog.setMessage("好友比对中...");
				progDialog.show();

				Thread thread = new Thread(new Runnable() {

					@Override
					public void run() {
						getPhoneContacts();
						getSIMContacts();

						try {
							writerFile();
						} catch (IOException e) {

							e.printStackTrace();
						}

						handler.sendEmptyMessage(0);
					}
				});

				thread.start();

			}
		});

		friendsListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Bundle bundle = new Bundle();
				bundle.putInt("id", myfriends.get(position).getFriendid());
				Log.i("mylog", "myfriends.get(position).getFriendid():"
						+ myfriends.get(position).getFriendid());
				bundle.putString("name", myfriends.get(position)
						.getFriendname());
				bundle.putString("mob", myfriends.get(position).getFriendmob());
				bundle.putString("cjh", myfriends.get(position).getFriendcar());
				bundle.putString("email", myfriends.get(position)
						.getFriendemail());
				bundle.putString("addr", myfriends.get(position).getAdress());
				Intent intent = new Intent(FriendAct.this, FriendView.class);
				intent.putExtras(bundle);
				startActivity(intent);
				FriendAct.this.finish();
			}
		});

		invetButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent it = new Intent(Intent.ACTION_VIEW);
				it.putExtra("sms_body",
						"您的好友邀请您使用Navi168，点击  http://navi168.net 查看下载应用!");
				it.setType("vnd.android-dir/mms-sms");
				startActivity(it);

			}
		});

		newfriend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(0);

			}
		});
		sendmesButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				if (bundle != null) {
					Log.i("mylog", "bundle is not null!");
				}
				if (numbermap.size() < 1) {
					showToast("请至少选择一个号码？");
				} else {
					bundle.putString("postnum", getNumberText(numbermap));
					bundle.putSerializable("postname", getNumberText(namemap));
					Intent intent = new Intent(FriendAct.this, Sendmes.class);
					intent.putExtra("sendmeslist", bundle);
					startActivity(intent);
				}
			}
		});

	}

	private void findViews() {

		newfriend = (Button) findViewById(R.id.addnewfriend2);
		friendsListView = (ListView) findViewById(R.id.myfriendlist_id2);
		sendmesButton = (Button) findViewById(R.id.sendmes);
		synButton = (Button) findViewById(R.id.synfriend);
		invetButton = (Button) findViewById(R.id.dxbutton);

	}

	@SuppressWarnings({ "unused", "rawtypes" })
	private String getNumberText(HashMap<String, String> nums) {
		Iterator<Entry<String, String>> iter = nums.entrySet().iterator();
		String newnum = "";
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			newnum += entry.getValue() + " ";
		}

		return newnum;

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new Builder(this);

		if (id == 0) {

			LayoutInflater inflater = LayoutInflater.from(this);
			// 获取相关的布局
			final View layout = inflater
					.inflate(R.layout.newfrienddialog, null);
			Button addButton = (Button) layout.findViewById(R.id.add);
			addButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					final TableLayout tableLayout = (TableLayout) layout
							.findViewById(R.id.tablelayout2);
					numer = tableLayout.getChildCount();

					TableRow tRow = new TableRow(FriendAct.this);
					TableLayout.LayoutParams tlp = new TableLayout.LayoutParams(
							LayoutParams.MATCH_PARENT,
							LayoutParams.WRAP_CONTENT);
					TableRow.LayoutParams trl = new TableRow.LayoutParams(
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);
					tRow.setLayoutParams(tlp);
					TextView tView = new TextView(FriendAct.this);
					tView.setText("车机号 " + (numer - 3));
					EditText edit = new EditText(FriendAct.this);
					final Button delButton = new Button(FriendAct.this);
					delButton.setId(numer);
					delButton.setText("del");
					delButton.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Log.i("mylog", delButton.getId() + "");
							tableLayout.removeView(trs.get(delButton.getId()
									+ ""));
							editHashtable.remove(delButton.getId()+"");

						}
					});

					tView.setLayoutParams(trl);
					edit.setLayoutParams(trl);
					delButton.setLayoutParams(trl);

					tRow.addView(tView);
					tRow.addView(edit);
					tRow.addView(delButton);
					trs.put(numer + "", tRow);
					editHashtable.put(numer + "", edit);
//					ets.add(edit);
					tableLayout.addView(tRow);

				}
			});

			builder.setView(layout);
			builder.setTitle("增加一个新的好友！");
			builder.setPositiveButton("保存",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							ArrayList<Cheji> chejis = new ArrayList<Cheji>();
							EditText friendname = (EditText) layout
									.findViewById(R.id.friendname);
							EditText friendmob = (EditText) layout
									.findViewById(R.id.friendmob);

							EditText friendemail = (EditText) layout
									.findViewById(R.id.friendemail);
							Myfriend mf = new Myfriend();
							mf.setFriendemail(friendemail.getText().toString()
									.trim());

							mf.setFriendname(friendname.getText().toString()
									.trim());
							mf.setFriendmob(friendmob.getText().toString()
									.trim());
							
							if (editHashtable.size() > 0) {

								Enumeration   eunm = editHashtable.keys();
								while (eunm.hasMoreElements()) {
									Cheji cj = new Cheji();
									String key = (String) eunm.nextElement();
									cj.setCheji(editHashtable.get(key).getText().toString());
									cj.setMobile(friendmob.getText().toString()
											.trim());
									chejis.add(cj);
									
								}

								int flag2 = sqlh.saveChejis(chejis);
							}

							int flag = sqlh.add_Newmyfriend(mf);
							if (flag > 0) {
								showToast("增加新用户成功！");
							} else {
								showToast("增加新用户失败！");
							}
							myfriends = sqlh.getMyfriends();
							mAdapter.notifyDataSetChanged();
							dialog.dismiss();

						}
					});
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();

						}
					});

		}
		return builder.create();

	}

	public class MyAdapter extends BaseAdapter {
		ViewHolder vHolder = null;

		@Override
		public int getCount() {
			//
			return myfriends.size();
		}

		@Override
		public Object getItem(int arg0) {
			//
			return myfriends.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			//
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			if (convertView == null) {
				vHolder = new ViewHolder();
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.myfriend_c, parent,
						false);
				vHolder.fname = (TextView) convertView
						.findViewById(R.id.friendname);
				vHolder.fstate = (TextView) convertView
						.findViewById(R.id.friendstate);
				vHolder.selected = (CheckBox) convertView
						.findViewById(R.id.ischecked);
				convertView.setTag(vHolder);

			} else {
				vHolder = (ViewHolder) convertView.getTag();
			}

			vHolder.fname.setText(myfriends.get(position).getFriendname());
			if (myfriends.get(position).getFriendstate() == "1") {
				vHolder.fstate.setText("在线");
			} else {
				vHolder.fstate.setText("离线");
			}
			vHolder.selected.setChecked(false);
			vHolder.selected
					.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(
								final CompoundButton buttonView,

								boolean isChecked) {

							if (isChecked) {
								if (isenable > 1) {
									buttonView.setChecked(false);
								} else {
									isenable += 1;
									number_arry[0] = myfriends.get(position)
											.getFriendmob() == null ? "无此会员手机号"
											: myfriends.get(position)
													.getFriendmob();
									number_arry[1] = myfriends.get(position)
											.getFriendcar() == null ? "无此会员车机号"
											: myfriends.get(position)
													.getFriendcar();

									AlertDialog.Builder builder = new Builder(
											FriendAct.this);
									builder.setTitle("请选择号码");

									builder.setItems(
											number_arry,
											new DialogInterface.OnClickListener() {

												public void onClick(
														DialogInterface dialog,
														int which) {

													if (!number_arry[which]
															.contains("无")) {

														numbermap.put(
																String.valueOf(position),
																number_arry[which]);
														namemap.put(
																String.valueOf(position),
																myfriends
																		.get(position)
																		.getFriendname());

													} else {
														buttonView
																.setChecked(false);
													}

												}

											});
									builder.create().show();

								}
								Log.i("mylog", isenable + "isenable");
							} else {

								isenable -= 1;
								numbermap.remove(String.valueOf(position));
								namemap.remove(String.valueOf(position));

							}

						}

					});

			return convertView;
		}

	}

	public class ViewHolder {
		public CheckBox selected;
		public TextView fname;
		public TextView fstate;
	}

	private void getPhoneContacts() {
		ContentResolver resolver = context.getContentResolver();

		// 获取手机联系人
		Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,
				PHONES_PROJECTION, null, null, null);

		if (phoneCursor != null) {
			while (phoneCursor.moveToNext()) {

				// 得到手机号码
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				// 当手机号码为空的或者为空字段 跳过当前循环
				if (phoneNumber.length() != 11)
					continue;

				// 得到联系人名称
				String contactName = phoneCursor
						.getString(PHONES_DISPLAY_NAME_INDEX);

				friendnumber.put(phoneNumber, contactName);

			}

			phoneCursor.close();
		}
	}

	private void getSIMContacts() {
		ContentResolver resolver = context.getContentResolver();
		// 获取Sims卡联系人
		Uri uri = Uri.parse("content://icc/adn");
		Cursor phoneCursor = resolver.query(uri, PHONES_PROJECTION, null, null,
				null);

		if (phoneCursor != null) {
			while (phoneCursor.moveToNext()) {

				// 得到手机号码
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				// 当手机号码为空的或者为空字段 跳过当前循环
				// 得到联系人名称
				String contactName = phoneCursor
						.getString(PHONES_DISPLAY_NAME_INDEX);

				friendnumber.put(phoneNumber, contactName);
			}

			phoneCursor.close();
		}
	}

	private void writerFile() throws IOException {
		String filename = "txl.txt";
		String filecontent = "";
		Iterator iter = friendnumber.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = entry.getKey().toString();
			String val = entry.getValue().toString();
			filecontent += val + "|" + key + "||";
		}

		FileOutputStream outStream = context.openFileOutput(filename,
				Context.MODE_PRIVATE);
		outStream.write(filecontent.getBytes());
		outStream.close();
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				progDialog.dismiss();
				showToast("好友比对完成！");
			}
		}
	};
}
